
async function getCurrentTab() {
  let queryOptions = { active: true, lastFocusedWindow: true };
  // `tab` will either be a `tabs.Tab` instance or `undefined`.
  let [tab] = await chrome.tabs.query(queryOptions);
  return tab;
}

// 给页面设置隐藏样式
function addHiddenClass(sec, tabId) {

  function settingSingle(selector) {
    let htmlColl = document.querySelectorAll(selector)

    Array.from(htmlColl).forEach(item => {
      item.classList.add('biliHidden')
    })
  }
  chrome.scripting.executeScript({
    target: { tabId: tabId },
    func: settingSingle,
    args: [sec]
  })
}


// 监听页面加载事件
// chrome.webNavigation.onCompleted.addListener(async () => {
//   // 添加样式
//   let tab = await getCurrentTab()
//   await chrome.scripting.insertCSS({
//     css: '.biliHidden{display:none!important;}',
//     target: { tabId: tab.id }
//   })
//   // 获取未勾选的属性(不显示)
//   let { treeData } = await chrome.storage.sync.get("treeData")

//   let { checkedKeys } = await chrome.storage.sync.get("checkedKeys")

//   let flatTreeKeyPathObj = {}
//   treeData.forEach(tree => {
//     flatTreeKeyPathObj[tree.id] = tree.path || ''
//     tree.children && tree.children.forEach(child => {
//       flatTreeKeyPathObj[child.id] = child.path
//     })
//   })

//   let allKeys = treeData.map(tree => [tree.id, tree?.children.map(node => node.id)]).flat().flat()
//   console.log('allKeys', allKeys)
//   console.log('checkedKeys', checkedKeys)

//   let unCheckedPaths = allKeys.filter(key => !checkedKeys.includes(key)).map(unckey => flatTreeKeyPathObj[unckey])

//   // 未选中的path，添加隐藏样式
//   setTimeout(() => {
//     unCheckedPaths.forEach(sec => {
//       if (sec) {
//         if (Array.isArray(sec)) {
//           sec.forEach(singleSec => addHiddenClass(singleSec, tab))
//         } else {
//           addHiddenClass(sec, tab)
//         }
//       }
//     })
//   }, 3000)

// }, {
//   url: [{ urlMatches: 'https://www.bilibili.com/video' }]
// })

// 监听网络请求
// https://api.bilibili.com/x/player/v2
// chrome.declarativeNetRequest.updateDynamicRules(
//   {
//     addRules: [
//       {
//         action: { type: 'block' },
//         condition: { requestDomains: ['api.bilibili.com'], urlFilter: 'v2' },
//         id: 41088
//       }
//     ]
//   },
//   () => {

//   }
// )

async function hiddenClassFunc({ tabId }) {
  //   添加样式
  await chrome.scripting.insertCSS({
    css: '.biliHidden{display:none!important;}',
    target: { tabId: tabId }
  })
  // 获取未勾选的属性(不显示)
  let { treeData } = await chrome.storage.sync.get("treeData")

  let { checkedKeys = [] } = await chrome.storage.sync.get("checkedKeys")

  let flatTreeKeyPathObj = {}
  treeData.forEach(tree => {
    flatTreeKeyPathObj[tree.id] = tree.path || ''
    tree.children && tree.children.forEach(child => {
      flatTreeKeyPathObj[child.id] = child.path
    })
  })

  let allKeys = treeData.map(tree => [tree.id, tree?.children.map(node => node.id)]).flat().flat()

  let unCheckedPaths = allKeys.filter(key => !checkedKeys.includes(key)).map(unckey => flatTreeKeyPathObj[unckey])

  // 未选中的path，添加隐藏样式
  chrome.alarms.create('scheduledTasks', { when: Date.now() + 2000 })

  chrome.alarms.onAlarm.addListener(
    (alarms) => {
      unCheckedPaths.forEach(sec => {
        if (sec) {
          if (Array.isArray(sec)) {
            sec.forEach(singleSec => addHiddenClass(singleSec, tabId))
          } else {
            addHiddenClass(sec, tabId)
          }
        }
      })
    }
  )

}


chrome.webRequest.onCompleted.addListener(
  hiddenClassFunc,
  { urls: ["*://api.bilibili.com/x/player/wbi/v2*", "*://api.bilibili.com/x/v2/reply/wbi/main*"], types: ["xmlhttprequest"] },
  ["responseHeaders", "extraHeaders"]
)


